package nz.ac.massey.jbuif.editor.components;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.Date;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;

import nz.ac.massey.jbuif.editor.BeanEditor;

import com.toedter.calendar.JCalendar;

/**
 * Class DateEditorPanel
 * @author AMIR H KIOUMARS
 *
 */
public class DateEditorPanel extends BaseComponent implements PropertyChangeListener,ActionListener {

	private static final long serialVersionUID = 1L;
	private JCalendar calendarField;
	private JFrame calendarFrame;
	private JLabel currentDate;
	
	
	/**
	 * DateEditorPanel
	 * @param p bean editor instance
	 * @param name string name
	 * @param displayName string name to be display
	 * @param pev an object
	 */
	public DateEditorPanel(BeanEditor p,String name,String displayName,Object pev){
		super(p,name,displayName, pev);
		
		calendarFrame = new JFrame();
		calendarFrame.setSize(400, 300);
		calendarField = new JCalendar();
		calendarField.getDayChooser().addPropertyChangeListener(this);
		calendarField.getMonthChooser().addPropertyChangeListener(this);
		calendarField.getYearChooser().addPropertyChangeListener(this);
		
		currentDate = new JLabel();
		
		if(pev!=null){
			calendarField.setDate((Date)pev);
			currentDate.setText("Date: "+pev.toString());
		} else {
			currentDate.setText("Date: not set");
		}
		
		JButton openCalendar = new JButton();
		openCalendar.setActionCommand("opencalendar");
		openCalendar.addActionListener(this);
		openCalendar.setText("Edit Date");
		
		calendarFrame.add(calendarField);
		super.addPropertyComponent(currentDate);	
		super.addPropertyComponent(openCalendar);
	}
	
	
	/**
	 * getDate get the date
	 * @return date instance
	 */
	private Date getDate(){
		return calendarField.getDate();
	}
	
	
	/**
	 * refreshDateField refresh the field date
	 */
	private void refreshDateField(){
		currentDate.setText("Date: "+super.getPropertyValue());
	}

	
	/**
	 * propertyChange controls the property change event
	 * @param e PropertyChangeEvent instance
	 */
	@Override
	public void propertyChange(PropertyChangeEvent e) {
		ActionEvent e1 = new ActionEvent(e.getSource(), e.hashCode(), "dateChanged");
		super.setPropertyValue(this.getDate());
		e1.setSource(this);
		super.getBeanEditor().actionPerformed(e1);
		refreshDateField();
	}

	
	/**
	 * actionPerformed controls the action performed event
	 * @param arg0 ActionEvent instance
	 */
	@Override
	public void actionPerformed(ActionEvent arg0) {
		if(arg0.getActionCommand().equals("opencalendar")){
			calendarFrame.setVisible(true);
		}
	}
}
